package web.jdbc.function;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.StringJoiner;

import web.clazz.Clazz;
import web.jdbc.DataOperator;

/**用于添加Entity
 * @author 乐渊
 * @version 1.0
 * @see DataOperator
 * */
public class Insert<T>{
	
	private static PreparedStatement ps = null;
	private Connection conn = null;
	private T t;
	private Clazz clazz = null;
	
	public Insert(Connection conn,T t,Clazz clazz) {
		this.conn = conn;
		this.t = t;
		this.clazz = clazz;
	}
	
	public boolean getRS() throws SQLException{
		StringJoiner sql = new StringJoiner("");
		sql.add("INSERT INTO "+clazz.getName()+"(");
		new DataOperator<T>().collectData(t,clazz);
		
		for(String column:DataOperator.columns){
			sql.add(column+",");
		}
		sql.add(") VALUES (");
		
		for(int i=0;i<DataOperator.values.size();i++){
			sql.add("?,");
		}
		sql.add(")");
		ps = conn.prepareStatement(sql.toString().replaceAll(",\\)", "\\)"));
		
		for(int i = 1;i<=DataOperator.values.size();i++)
			DataOperator.setData(ps,i, DataOperator.values.get(i-1));
		
		boolean b = ps.execute();
		ps.close();
		
		return b;
	}
	

	
	
}
